import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { RoleEntity } from 'src/entity/role.entity';
import { UserRoleEntity } from 'src/entity/user.role.entity';
import { RolesDto } from 'src/modules/background/role/dto/roles.dto';
import { RoleListDto } from 'src/modules/background/role/dto/roles.list.dto';
import { RoleListVo } from 'src/modules/background/role/vo/role.vo';
import { getRepository, Repository } from 'typeorm';
interface UserRoleType {
    userId: number;
    roleIds: number[];
}
@Injectable()
export class RoleService {

    constructor(
        @InjectRepository(RoleEntity)
        private readonly roleRepository: Repository<RoleEntity>,
        @InjectRepository(UserRoleEntity)
        private readonly userRoleRepository: Repository<UserRoleEntity>,
    ) { }
    // 增
    async add(rolesDto: RolesDto): Promise<string> {
        try {
            const { rolename } = rolesDto
            const isHave = await this.roleRepository.findOne({ where: { rolename } })
            if (isHave) {
                return '创建失败,已经存在该角色';
            } else {
                const account = this.roleRepository.create({
                    ...rolesDto,
                });
                await this.roleRepository.save(account);
                return '创建成功';
            }
        } catch (error) {
            return error
        }
    }
    // 删
    async remove(id: number): Promise<string> {
        const result = await this.roleRepository.softDelete(id)//软删除数据库记录还在 但是查出来的是未删除的数据
        if (result) {
            return "删除成功"
        } else {
            return '删除失败'
        }
    }
    // 改
    async update(id: number, rolesDto: RolesDto): Promise<string> {
        try {
            const { rolename, description,isDefault} = rolesDto
            const result = await this.roleRepository.findOne(id);
            await this.roleRepository.save(Object.assign(result, { rolename, description,isDefault}))
            return "更新成功"
        } catch (error) {
            return '更新失败'
        }

    }
    // 根据id 单条查询
    async findById(id: number): Promise<any> {
        // 根据id 用户查询
        const result = await this.roleRepository.findOne(id);
        return result;
    }
    // 查询全部
    async findAll(data: RoleListDto): Promise<RoleListVo> {
        // pageNumber :当前页 pageSize:一页几条    v查询得用 or
        const { pageNum, pageSize, rolename} = data
        const qb = await getRepository(RoleEntity)
            .createQueryBuilder('role')
        if (rolename) {
            qb.andWhere("role.username LIKE :username", { username: `%${rolename}%` });
        }
        qb.printSql();
        qb.orderBy('role.updated_at', 'DESC');
        const total = await qb.getCount();
        if(pageNum && pageSize){
            qb.skip((pageNum - 1) * pageSize);
            qb.take(pageSize)
        }
        const result = await qb.getMany();
        return {
            roles: result,
            total,
            pageNum,
            pageSize
        }
    }
    // 分配角色
    async distributionRole(data: UserRoleType): Promise<boolean>{
        try {
            const {roleIds,userId} = data
            await this.userRoleRepository.delete(userId)
            for(let i=0;i<roleIds.length;i++){
                const roleAccount =  this.userRoleRepository.create({
                    userId,
                    roleId:Number(roleIds[i])
                })
                await this.userRoleRepository.save(roleAccount)
            }
            return true
        } catch (error) {
            return false
        }
        
    }
}
